package com.wy.panda.common.util;

import org.springframework.util.Assert;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;

/**
 * bean工具类
 * @author wangyuan
 * @since 2019年6月5日 下午9:54:25
 *
 */
public class BeanUtils extends org.springframework.beans.BeanUtils {

    private static MapperFactory mapperFactory;
    private static MapperFacade mapperFacade;
    
    public static void init(MapperFactory mapperFactory) {
        BeanUtils.mapperFactory = mapperFactory;
        BeanUtils.mapperFacade = mapperFactory.getMapperFacade();
    }
    
    public static MapperFactory mapperFactory() {
        Assert.notNull(mapperFactory, "mapperFactory不能为空");
        return BeanUtils.mapperFactory;
    }
    
    public static MapperFacade mapperFacade() {
        Assert.notNull(mapperFacade, "mapperFacade不能为空");
        return BeanUtils.mapperFacade;
    }
    
    public static <S, D> D convert(S sourceObject, Class<D> destinationClass) {
        Assert.notNull(mapperFactory, "mapperFactory不能为空");
        Assert.notNull(mapperFacade, "mapperFacade不能为空");
        
        if(null == sourceObject) {
            return null;
        }
        
        mapperFactory.classMap(sourceObject.getClass(), destinationClass)
            .mapNulls(true)
            .mapNullsInReverse(true);
        
        return mapperFacade.map(sourceObject, destinationClass);
    }
}
